<template>
  <div class="box2">
    <van-field
      v-model="sms"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button size="small" type="default" :disabled="flag" @click="dosendmsgcodeFn">{{text}}</van-button>
      </template>
    </van-field>
    <van-button
      round
      block
      @click="docheckcodeFn"
      :disabled="!flagBtn"
      color="#ff6666"
      style="margin-top: 20px">下一步
    </van-button>
  </div>
</template>
<script>
import Vue from 'vue'

import {
  Button,
  Field,
  Dialog
} from 'vant'

import { dosendmsgcode, docheckcode } from '@/api/register'

Vue.use(Field)
Vue.use(Button)
Vue.use(Dialog)

export default {
  name: 'step2',
  data () {
    return {
      sms: '',
      time: '6',
      text: '发送验证码',
      timer: null,
      flag: true
    }
  },
  computed: {
    flagBtn () {
      return /^\d{5}$/.test(this.sms)
    }
  },
  mounted () {
    dosendmsgcode({ tel: localStorage.getItem('tel') }).then(res => {
      console.log('mounted', res.data.data)
    })
    this.countReduce()
  },
  methods: {
    dosendmsgcodeFn () {
      this.countReduce()
      this.time = 6
      dosendmsgcode({ tel: localStorage.getItem('tel') }).then(res => {
        this.sms = res.data.data
      })
    },
    docheckcodeFn () {
      docheckcode({ tel: localStorage.getItem('tel'), telcode: this.sms }).then((res) => {
        console.log(localStorage.getItem('tel'), res.data, res.data.code, res.data.code !== '200')
        console.log(this.sms)
        if (res.data.code !== '200') {
          Dialog.confirm({
            message: '验证码错误',
            confirmButtonText: '重新发送验证码',
            cancelButtonText: '取消'
          })
            .then(() => {
              // on confirm
              // this.dosendmsgcodeFn()
            })
            .catch(() => {
              // on cancel
            })
        } else {
          this.$router.push('step3')
        }
      })
    },
    countReduce () {
      this.flag = true
      this.timer = setInterval(() => {
        this.time--
        if (this.time <= 0) {
          this.flag = false
          this.text = '发送验证码'
          clearInterval(this.timer)
          return
        }
        this.text = this.time + 's后发送验证码'
      }, 1000)
    }
  }
}
</script>

<style scoped>

</style>
